import React, { useEffect, useState } from 'react';
import { Button, Spin, Tabs, Typography, Space, message, Tooltip, Row, Col } from 'antd';
import { ReloadOutlined, TableOutlined, AppstoreOutlined } from '@ant-design/icons';
import { useLanguage } from '../../i18n/I18nProvider';
import { apiService } from '../../services';
import ProjectTable from '../../components/Project/ProjectTable';
import ProjectCard, { ProjectNode } from '../../components/Project/ProjectCard';
import './Projects.scss';
import {NodeModulesScanResult, ProjectSimpleTree} from "../../../types";

const { Title, Paragraph } = Typography;
const { TabPane } = Tabs;

// 视图类型
type ViewType = 'table' | 'card';

const Projects: React.FC = () => {
  const { t } = useLanguage();
  const [projects, setProjects] = useState<ProjectSimpleTree[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [viewType, setViewType] = useState<ViewType>('table');
  const [messageApi, contextHolder] = message.useMessage();

  // 扫描项目
  const scanProjects = async () => {
    try {
      setLoading(true);
      messageApi.loading({ content: t('projects.scanning'), key: 'scan', duration: 0 });
      const response = await apiService.projects.scan();
      // 确保响应是数组
      const data = response ? response.projects || [] : [];
      setProjects(data);
      messageApi.success({ content: t('projects.scanSuccess'), key: 'scan' });
    } catch (error) {
      console.error('扫描项目失败:', error);
      messageApi.error({ content: t('projects.scanFailed'), key: 'scan' });
    } finally {
      setLoading(false);
    }
  };

  // 切换视图
  const toggleView = (type: ViewType) => {
    setViewType(type);
  };

  useEffect(() => {
    scanProjects();
  }, []);

  return (
    <div className="projects-page page-container">
      {contextHolder}
      <div className="page-header flex-between">
        <div>
          <Title level={2}>{t('projects.title')}</Title>
          <Paragraph className="page-description">
            {t('projects.description')}
          </Paragraph>
        </div>
        <Space>
          <Tooltip title={t('projects.viewAsTable')}>
            <Button
              type={viewType === 'table' ? 'primary' : 'default'}
              icon={<TableOutlined />}
              onClick={() => toggleView('table')}
            />
          </Tooltip>
          <Tooltip title={t('projects.viewAsCard')}>
            <Button
              type={viewType === 'card' ? 'primary' : 'default'}
              icon={<AppstoreOutlined />}
              onClick={() => toggleView('card')}
            />
          </Tooltip>
          <Button
            type="default"
            icon={<ReloadOutlined />}
            onClick={scanProjects}
          >
            {t('projects.rescan')}
          </Button>
        </Space>
      </div>

      <div className="projects-content">
        {loading ? (
          <div className="loading-container">
            <Spin size="large" />
            <p>{t('projects.scanning')}</p>
          </div>
        ) : projects.length === 0 ? (
          <div className="empty-container">
            <p>{t('projects.noProjects')}</p>
            <Button type="primary" onClick={scanProjects}>
              {t('projects.rescan')}
            </Button>
          </div>
        ) : (
          <>
            {viewType === 'table' ? (
              <ProjectTable projects={projects} />
            ) : (
              <div className="projects-card-grid">
                <Row gutter={[16, 16]}>
                  {projects.map(project => (
                    <Col xs={24} sm={12} md={8} lg={6} key={project.path}>
                      <ProjectCard project={project} />
                    </Col>
                  ))}
                </Row>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default Projects;
